clc;clear;clearvars;
addpath('CEC2008\');
javaclasspath('CEC2008\FractalFunctions.jar');
global initial_flag

NS = 100;   % 种群数
dim = 500;   % 种群维度
upper_bound = [100,100,100,5,600,32,1];    % 搜索区间
lower_bound = [-100,-100,-100,-5,-600,-32,-1];
bestYhistory = [];    % 保存每次迭代的最佳值
sList = [5,10,25,50,100];   % 组大小池
sHistory = [];
evaluation = 0;
maxEvaluation = 2.5 * 10 ^ 6;

for func_num = 3

    initial_flag = 0;    % 换一个函数initial_flag重置为0
    sample_x = lhsdesign(NS, dim).*(upper_bound(func_num) - lower_bound(func_num)) + lower_bound(func_num).*ones(NS, dim);    % 生成NS个种群,并获得其评估值
    sample_y = benchmark_func(sample_x,func_num);
    evaluation = evaluation + NS;
    [best_y, bestIndex] = min(sample_y);    % 获取全局最小值以及对应的种群
    best_x = sample_x(bestIndex,:);
    preBestY = best_y;
    bestYhistory = [bestYhistory; best_y];

    while evaluation < maxEvaluation    
%         if evaluation == NS || preBestY > best_y + 0.001
%             s = sList(randi(5));    % 利用随机方式来获得子空间数目            
%         else
%             preBestY = best_y;
%         end
        s = sList(randi(5)); 
        index = randperm(dim);      % 随机划分子空间
        for i1 = 1 : s
            index1 = index(((i1 - 1) * (dim / s) + 1) : (i1 * (dim / s)));
            sub_x = sample_x(:,index1);
            sub_x = SaNSDE(sub_x, sample_y, best_x, index1, 10, dim / s, lower_bound(func_num), upper_bound(func_num), @(x)benchmark_func(x,func_num));%200*1
            sample_x(:,index1) = sub_x;     % 1效果不好,10相当于提供更多的迭代次数
            sample_y = benchmark_func(sample_x,func_num);
            evaluation = evaluation + 11 * NS;
            [best_y, bestIndex] = min(sample_y);    % 获取全局最小值以及对应的种群
            best_x = sample_x(bestIndex,:);
        end
        sHistory = [sHistory;s];
        bestYhistory = [bestYhistory; best_y];
        disp(best_y);
    end
end
figure(1);
plot(bestYhistory);
figure(2);
plot(sHistory);